package de.tum.activities.SecondExamEvaluation;

import java.util.ArrayList;
import java.util.List;

import org.xmlrpc.android.XMLRPCException;

import de.tum.ExamApp.R;
import de.tum.Misc.Variables;
import de.tum.activities.StatsApp.AchievedPointsBarChart;
import de.tum.control.Synchronizer;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SecondExamEvaluationActivity extends Activity{
	
	public static int FURTHER_SECOND_CORRECTION = 100;
	
	private int examId;
	
	private String examName;
	
	private Bundle extras;
	
	private EditText curEditText;
	
	double[] maxPoints;
	
	int nbrOfExams;
	
	int workedExamId;
	
	List<EditText> editTextes;
	
	List<Integer> firstCorrectExercises;
	
	Dialog dialog;
	
	Dialog endDialog;
	
	EditText editTextMatrNr;
	
	String studentMatrNr;
	
	String studentName;
	
	LinearLayout verticalLayout;
	
	Context context;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
      	setContentView(R.layout.second_evaluation);
      	
      	this.context = context;
      	
      	extras = getIntent().getExtras();     
        examId = extras.getInt("examID");
        examName = extras.getString("examName");
      
        TextView headline = (TextView) findViewById(R.id.second_evaluation_headline);
		headline.setText(getString(R.string.second_evaluation_headline, examName));
	
		verticalLayout = (LinearLayout) findViewById(R.id.second_evaluation_linear_layout);
		
		
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); // Verbose!
		lp.setMargins(0, 12, 0, 12);
		
		TextView addEvaluation = new TextView(getApplicationContext());
		addEvaluation.setText("+ add second evaluation");
		addEvaluation.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
		addEvaluation.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				sendEvaluationToServer();
				
				endDialog = new Dialog(SecondExamEvaluationActivity.this);
				endDialog.setContentView(R.layout.secondevaluateenddialog);
		        endDialog.setTitle(getString(R.string.second_evaluation_finished));
		        endDialog.setCancelable(false);
		        
		        Button newSecondEvaluationButton = (Button) endDialog.findViewById(R.id.newSecondEvaluationButton);
		        Button backToEvaluationOverviewButtonSecondEnd = (Button) endDialog.findViewById(R.id.backToOverviewEndEvaluationSecond);
		        
		        newSecondEvaluationButton.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
				        endDialog.dismiss();
						Intent resultIntent =  new Intent();
						resultIntent.putExtra("examID", examId);
						resultIntent.putExtra("examName", examName);
						setResult(FURTHER_SECOND_CORRECTION, resultIntent);
						finish();
						
					}
				});
		        
		        backToEvaluationOverviewButtonSecondEnd.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
				        endDialog.dismiss();
						Intent resultIntent =  new Intent();;
						setResult(RESULT_OK, resultIntent);
						finish();
					}
				});
				
		        endDialog.show();
			}

		});
		
		verticalLayout.addView(addEvaluation, lp);
		
		
		nbrOfExams = 0;
		maxPoints = new double[0];
		firstCorrectExercises = new ArrayList<Integer>();
		
		Synchronizer sync = new Synchronizer();
		try {
			nbrOfExams = sync.getNumberOfExercisesInExam(examId);
			maxPoints = new double[nbrOfExams];
			
			for(int i=0; i<nbrOfExams; i++){
				maxPoints[i] = sync.getMaxPointsToExerciseType(examId, i+1);
			}
			
		} catch (XMLRPCException e) {
			TextView errorTextView = new TextView(getApplicationContext());
			errorTextView.setText("Error loading the number of exercises!");
			verticalLayout.addView(verticalLayout);
		}
		
		editTextes = new ArrayList<EditText>();
		
		for(int i=0; i< nbrOfExams; i++){
			
			final int curCount = i;
			curEditText = new EditText(getApplicationContext());
			curEditText.setHint("Points in Exercise "+(curCount+1));
			curEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
			curEditText.setEnabled(false);
			editTextes.add(curEditText);
			
			
			curEditText.addTextChangedListener(new TextWatcher() {
				
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					
				}
				
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {
				}
				
				@Override
				public void afterTextChanged(Editable s) {
					
					if(editTextes.get(curCount).getText().toString().isEmpty())
						return;
					
					Double  textEditAchievedPoints = new Double(editTextes.get(curCount).getText().toString());
					if(maxPoints[curCount] < textEditAchievedPoints){
						Log.d("second evaluation", "curCounter = "+curCount);
						Toast.makeText(getApplicationContext(), "Pay attention to maximum", Toast.LENGTH_SHORT).show();
						editTextes.get(curCount).setText(""+0);
					}else{
					
						double floatOfAchievedPoints = (textEditAchievedPoints - (int) Math.floor(textEditAchievedPoints));
						
						if((floatOfAchievedPoints != 0) && 
								(floatOfAchievedPoints != 0.5)){
								Toast.makeText(getApplicationContext(), "Only .5 results!", Toast.LENGTH_SHORT).show();
								Log.d("Exam Evaluation", "Float: "+floatOfAchievedPoints);
								if(floatOfAchievedPoints < 0.25)
									floatOfAchievedPoints = 0;
								else if(floatOfAchievedPoints < 0.75)
									floatOfAchievedPoints = 0.5;
								else
									floatOfAchievedPoints = 1;
								
								Log.d("Exam Evaluation", "Float: "+floatOfAchievedPoints);
								
								editTextes.get(curCount).setText(""+((int) Math.floor(textEditAchievedPoints)+floatOfAchievedPoints));
						}
					}
					
				}
			});
		}
		
      
		
		
		 	dialog = new Dialog(SecondExamEvaluationActivity.this);
	        dialog.setContentView(R.layout.secondevaluatedialog);
	        dialog.setTitle(getString(R.string.add_second_evaluation_to, examName));
	        dialog.setCancelable(false);
	        
	        editTextMatrNr = (EditText) dialog.findViewById(R.id.EditTextMatrNrSecond);
	        Button startEvaluationButton = (Button) dialog.findViewById(R.id.startEvaluationButtonSecond);
	        Button backToEvaluationOverviewButton = (Button) dialog.findViewById(R.id.backToEvaluationOverviewSecond);
	        
	        startEvaluationButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					/**
			         * Setting the contentView to start the activity
			         */
					
					studentMatrNr = editTextMatrNr.getText().toString();
					
					if(!studentMatrNr.matches("[a-zA-Z0-9]+")){
						Toast.makeText(getApplicationContext(), "No special character", Toast.LENGTH_LONG).show();
						return;
					}
					
					Synchronizer sync = new Synchronizer();
					
					try {
						workedExamId = sync.getWorkedExamToExamIdAndMatrNr(examId, studentMatrNr);
						if(workedExamId > 0){
							
							firstCorrectExercises = sync.getFirstCorrectedExams(workedExamId);
							Log.d("Second Evaluation", "The first correctedExercises size: "+firstCorrectExercises.size());
							for (int firstCorrectExercise : firstCorrectExercises) {
								Log.d("second correctoin", "Enabling " + (firstCorrectExercise-1));
								editTextes.get(firstCorrectExercise-1).setEnabled(true);
							}
							
							for(EditText addEditText: editTextes){
								verticalLayout.addView(addEditText);
							}
							dialog.dismiss();
							

							
							
					        
						}else{
							Toast.makeText(getApplicationContext(), "Student not found! No first evaluation?", Toast.LENGTH_SHORT).show();	
						}
							
					} catch (XMLRPCException e) {
						e.printStackTrace();						
						Toast.makeText(getApplicationContext(), "Student not found! No first evaluation?", Toast.LENGTH_SHORT).show();
						return;
					}
					
					
				}
			});
	        
	        backToEvaluationOverviewButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent resultIntent =  new Intent();
					setResult(RESULT_OK, resultIntent);
					finish();
				}
			});
	        
	        dialog.show();
			
    }
    
    private void sendEvaluationToServer() {

		Synchronizer sync = new Synchronizer();
		
		int exerciseNumber = 1;
		for(EditText evaluationEditText : editTextes){
			
			String curResultString = evaluationEditText.getText().toString();
			
			if(!curResultString.isEmpty()){
				double curResult = new Double(curResultString);
				try {
					sync.addOrUpdateSecondCorrection(workedExamId, exerciseNumber, curResult);
				} catch (XMLRPCException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			exerciseNumber++;
			
			
		}			
    	
	}
    
    
}
